<template>
  <contentModel
    v-if="modelValue"
    :has-footer="false"
    title="详情"
    @open="open"
    @close="cancel"
  >
    <table-container
      v-model:columns="columns"
      :show-full-screen="false"
      :loading="detailTableLoading"
      :all-columns="allColumns"
      style="height: calc(100% - 20px)"
      @refresh="getDetailTableList"
    >
      <template #container-side>
        <a-button
          v-if="!canNotEdit"
          v-permission="['pms:receive-detail-batch:saveAll']"
          type="primary"
          @click="addRoot"
        >
          {{ Number(activeTab) === 2 ? '添加根节点' : '添加' }}
        </a-button>
        <a-button
          v-if="Number(activeTab) === 2"
          type="primary"
          @click="goToThreeCode"
          >三码验证</a-button
        >
      </template>
      <standard-table
        ref="detailTable"
        v-model:selectedKeys="detailSelectedKeys"
        :component-config="tableComponentConfig"
        :render-config="tableRenderConfig"
        :render-keys="detailTableRenderKeys"
        :loading="detailTableLoading"
        :data="detailTableData"
        :total="detailTableTotal"
        :columns="columns"
        @init-columns-end="initColumns"
        @page-change="detailPageChange"
        @page-size-change="detailPageSizeChange"
      >
        <!-- 非成品和非手动录入才可以更新dcd信息 -->
        <template #operate="{ record, rowIndex }">
          <a-button
            v-permission="['pms:dcd-sn-mian:updateDetailDcd']"
            type="text"
            :hidden="
              Number(activeTab) !== 2 || Number(record.setupSource) === 1
            "
            @click="handleDcd(record, rowIndex)"
            >更新DCD信息</a-button
          >
          <a-button
            v-permission="['pms:receive-detail-batch:updateAll']"
            type="text"
            :hidden="canNotEdit"
            @click="handleEdit(record, rowIndex)"
            >编辑</a-button
          >
          <a-button
            v-permission="['pms:receive-detail-batch:deleteAll']"
            type="text"
            :hidden="canNotEdit"
            @click="handleDelete(record, rowIndex)"
            >删除</a-button
          >
        </template>
      </standard-table>
    </table-container>
  </contentModel>
  <EditModal
    v-if="editModelVisible"
    v-model="editModelVisible"
    :select-id="selectBatchId"
    @fetch-data="getDetailTableList"
  ></EditModal>
</template>

<script lang="ts" setup>
  import { computed, defineAsyncComponent, inject, ref, toRefs } from 'vue';
  import {
    deletePmsReceiveBatch,
    getPmsReceiveBatchPage,
  } from '@/api/purchaseArrival/purchaseArrivalDetails';
  import { info } from '@/common/utils/modal-promise';
  import { updateDetailDcd } from '@/api/purchaseArrival/threeCodeVerification';
  import StandardTable from '@/common/components/standard-table/index.vue';
  import tableContainer from '@/common/components/table-container/index.vue';
  import { Message } from '@arco-design/web-vue';
  import { useRouter } from 'vue-router';
  import lodash from 'lodash';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '../moduleCommon/tableComp/baseTableConfig';

  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const EditModal = defineAsyncComponent(() => import('./EditModal.vue'));
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    // eslint-disable-next-line vue/require-prop-types
    selectId: {
      default: null,
    },
    // eslint-disable-next-line vue/require-prop-types
    activeTab: {},
  });
  const emits = defineEmits(['update:modelValue']);
  const cancel = () => {
    emits('update:modelValue', false);
  };
  const { selectId, activeTab } = toRefs(props);
  const router = useRouter();
  const selectBatchRow = inject('selectBatchRow');
  const columns = ref<object[]>([]);
  const allColumns = ref<object[]>([]);
  const initColumns = (data: any[]) => {
    columns.value = lodash.cloneDeep(data);
    allColumns.value = lodash.cloneDeep(data);
  };
  const canNotEdit = computed(() => {
    return Number(selectBatchRow.value.batchFlag) === 1;
  });
  // const { cancel } = useModelFun();
  // const loading = ref(false);
  const editModelVisible = ref(false);

  const detailTableRenderKeys = [
    'secretLevel',
    'setupSourceName',
    'mdsItemCode',
    'mdsItemName',
    'partQty',
    'reqQty',
    'recprtlotNo',
    'batchNo',
    'itemSerialNo',
    'suplyStatus',
    'invReceiveQty',
    'pmsReceiveQty',
    'operate300',
  ];
  // const handleSubmit = () => {
  //   cancel();
  // };
  // const handleCancel = () => {
  //   cancel();
  // };
  const open = () => {
    if (detailTableLoading.value) return;
    if (selectId?.value) {
      detailTableLoading.value = true;
      getDetailTableList();
    } else {
      detailTableLoading.value = false;
    }
  };
  // table-list
  const detailTable = ref(null);
  const selectBatchId = ref(null);
  // const detailRenderKeys = ['orderNo', 'mdsItemCode'];
  const detailSelectedKeys = ref([]);
  // let detailSelectRowList: Array<any> = [];
  const detailTableLoading = ref(false);
  const detailTableData = ref([]);
  const detailTableTotal = ref(0);
  // const selectDetailId = ref<string | number | null>(null);
  // const searchHandle = (query = {}) => {
  //   getDetailTableList(query);
  // };
  // const resetHandle = () => {
  //   getDetailTableList({});
  // };
  const handleEdit = (row) => {
    selectBatchId.value = row.id;
    editModelVisible.value = true;
  };
  const handleDelete = async (row) => {
    await info({
      title: '删除确认',
      content: '您确定要删除当前所选的数据？',
      okText: '确认',
    });
    const { id } = row;
    await deletePmsReceiveBatch(id);
    Message.success({
      content: '删除成功！',
      duration: 5 * 1000,
    });
    getDetailTableList();
  };
  const handleDcd = async (row) => {
    const form = {
      receiveDetailBatchId: row.id,
    };
    await updateDetailDcd(form);
    Message.success({
      content: '更新成功！',
      duration: 5 * 1000,
    });
  };
  const addRoot = () => {
    selectBatchId.value = null;
    editModelVisible.value = true;
  };
  const detailPageChange = () => {
    getDetailTableList();
  };
  const detailPageSizeChange = () => {
    getDetailTableList();
  };
  const goToThreeCode = () => {
    router.push({
      name: 'three-code-verification',
      query: {
        receiveDetailId: selectId.value,
      },
    });
  };
  const getDetailTableList = async (query = {}) => {
    const page = detailTable.value.getStatus();
    detailTableLoading.value = true;
    const { data } = await getPmsReceiveBatchPage({
      ...query,
      ...page,
      pmsReceiveDetailId: selectId.value,
    });
    detailTableData.value = data.list;
    detailTableTotal.value = data.total;
    detailTableLoading.value = false;
  };
  const init = () => {};
  init();
</script>

<style lang="less" scoped>
  @import url('../moduleCommon/common.less');
</style>
